<template>
  <div class="resourceApprove app-container">
    <div class="content">
      <div class="contentBox">
        <div class="search">
          <el-form
            :inline="true"
            :model="searchFrom"
            class="demo-form-inline"
            id="searchFrom"
          >
            <el-form-item>
              <el-input
                v-model="searchFrom.fileName"
                placeholder="文件名称"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-input
                placeholder="申请人"
                v-model="person"
                @click="activeDialog"
              ></el-input>
              <SelectDialog
                :dialog-param="SaleDialog"
                @ok="selectSales"
                @close="SaleDialog.isDialog = false"
              />
            </el-form-item>
            <el-form-item>
              <el-date-picker
                v-model="searchFrom.approveTime"
                value-format="YYYY-MM-DD"
                type="daterange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                @change="dateSelect"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="searchFrom.checkStatus"
                placeholder="申请状态"
                clearable
              >
                <el-option
                  v-for="item in process_approve_status"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-tree-select
                v-model="searchFrom.orgId"
                :data="department"
                :props="props"
                :height="208"
                placeholder="归属公司"
                clearable
                :disabled="needDisabled"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit"
                ><el-icon><Search /></el-icon>查询</el-button
              >
              <el-button type="default" @click="resetSearchFrom"
                ><el-icon><RefreshLeft /></el-icon>重置</el-button
              >
            </el-form-item>
          </el-form>
          <div>
            <el-button type="primary" plain @click="editEvent">
              <el-icon><Edit /></el-icon>编辑</el-button
            >
            <el-button @click="delEvent" type="primary" plain
              ><el-icon><DeleteFilled /></el-icon>删除</el-button
            >
          </div>
        </div>
        <div class="tableBox">
          <el-table
            :data="dataList"
            border
            stripe
            style="width: 100%"
            @selection-change="handleSelectionChange"
            @row-dblclick="editEvent"
            :header-cell-class-name="setClass"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="serialNo" label="申请编号" align="center" />
            <el-table-column prop="fileName" label="文件名称" min-width="220">
              <template #default="scope">
                <div class="filename" :title="scope.row.fileName">
                  {{ scope.row.fileName }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="fileAttribute"
              label="文件属性"
              width="110"
              align="center"
            />
            <el-table-column prop="checkName" label="审批状态" width="180">
              <template #default="scope">
                <!-- <dict-drop
                  :options="process_approve_status"
                  :value="scope.row.checkStatus"
                /> -->
                <div v-if="scope.row.checkName">
                  <span
                    class="dict-drop"
                    :class="scope.row.checkName === '审批通过' ? 'pass' : 'ing'"
                  ></span>
                  {{ scope.row.checkName }}
                </div>
                <div v-else>
                  <span class="dict-drop ing"></span>
                  {{ '暂未发起审批' }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="orgName" label="申请单位" align="center" />
            <el-table-column prop="deptName" label="申请部门" align="center" />
            <el-table-column
              prop="applicantName"
              label="申请人"
              width="100"
              align="center"
            />
            <el-table-column
              prop="createTime"
              label="申请时间"
              width="160"
              align="center"
            />
          </el-table>
          <pagination
            v-show="searchFrom.total > 0"
            :total="searchFrom.total"
            v-model:page="searchFrom.pageNum"
            v-model:limit="searchFrom.pageSize"
            @pagination="getList"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="resourceApprove">
import useCommonStore from '@/store/modules/common'
import { useRouter } from 'vue-router'
import { getCurrentInstance } from 'vue'
import { fileApplyList, fileApplyDel, fileAppDelList } from '@/api/fileManage'
import { format } from 'date-fns'
import { process_approve_status } from '@/hooks/dict/useProject'
import dictDrop from '@/components/DictDrop'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const commonStore = useCommonStore()
const { proxy } = getCurrentInstance()
const router = useRouter()
const props = {
  value: 'id',
  label: 'label',
  children: 'children'
}
// 省公司 查看全部 / 分公司 无法筛选
const needDisabled = computed(() => {
  return userStore.userInfo.orgId != '484'
})
// 申请人
const person = ref('')
const data = reactive({
  searchFrom: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    orgId: userStore.userInfo.orgId
  },
  selectData: [],
  dataList: [],
  SaleDialog: {},
  department: []
})

const { searchFrom, dataList, SaleDialog, selectData, department } =
  toRefs(data)
init()
async function init() {
  const res = await commonStore.getUseTreeData()
  department.value = await commonStore.getCompanyData()
  SaleDialog.value = {
    nodeKey: 'uuid',
    isDialog: false,
    data: [res[0]],
    multiple: false,
    defaultCheckedKeys: [],
    checkStrictly: false,
    title: '人员选择'
  }
  getList()
}
async function getList() {
  if (searchFrom.value.applicant) {
    searchFrom.value.applicant = searchFrom.value.applicant.replace(/U/g, '')
  }
  const fData = await fileApplyList(searchFrom.value)
  if (fData.code === 200) {
    dataList.value = fData.rows
    dataList.value.forEach(v => {
      v.createTime = format(new Date(v.createTime), 'yyyy-MM-dd HH:mm:ss')
    })
    searchFrom.value.total = fData.total
  }
}

function editEvent(row = {}) {
  if (!row.id && !selectData.value.length) {
    proxy.$modal.msgWarning('请先选择一条数据')
    return
  }
  if (!row.id && selectData.value.length > 1) {
    proxy.$modal.msgWarning('该功能仅支持单选')
    return
  }
  let fid, proInsId
  if (row && !row.id) {
    fid = selectData.value[0].id
    proInsId = selectData.value[0].proInsId
  } else {
    fid = row.id
    proInsId = row.proInsId
  }
  router.push({
    path: '/rsgl/other/editApprove',
    query: {
      id: fid,
      proInsId
    }
  })
}

function resetSearchFrom() {
  person.value = ''
  searchFrom.value.applicant = null
  searchFrom.value.fileName = null
  searchFrom.value.beginDate = null
  searchFrom.value.endDate = null
  searchFrom.value.checkStatus = null
  searchFrom.value.approveTime = []
  searchFrom.value.orgId = userStore.userInfo.orgId
  getList()
}

function onSubmit() {
  getList()
}

function delEvent() {
  if (!selectData.value.length) {
    proxy.$modal.msgWarning('请先选择一条数据')
    return
  }
  if (selectData.value.length === 1) {
    const id = selectData.value[0].id
    proxy.$modal
      .confirm('是否确认删除?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        fileApplyDel({ id }).then(res => {
          if (res.code === 200) {
            proxy.$modal.msgSuccess('删除成功')
            getList()
          }
        })
      })
  } else {
    const ids = selectData.value.map(v => v.id).toString()
    proxy.$modal
      .confirm('是否确认删除?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        fileAppDelList({ ids }).then(res => {
          if (res.code === 200) {
            proxy.$modal.msgSuccess('删除成功')
            console.log(res)
            getList()
          }
        })
      })
  }
}

function handleSelectionChange(row) {
  selectData.value = row
}

function activeDialog() {
  const defaultKey = searchFrom.value.applicant
    ? 'U' + searchFrom.value.applicant
    : ''
  SaleDialog.value.isDialog = true
  SaleDialog.value.defaultCheckedKeys = [defaultKey]
}

function selectSales(val) {
  console.log(val, 'default')
  person.value = val.labelData.join(',')
  SaleDialog.value.isDialog = false
  SaleDialog.value.defaultCheckedKeys = val.defaultCheckedKeys
  searchFrom.value.applicant = val.defaultCheckedKeys.join(',')
}

function dateSelect(val) {
  console.log(val)
  if (!val) {
    val = []
  }
  searchFrom.value.beginDate = val[0]
  searchFrom.value.endDate = val[1]
}

// 表头-- 审批状态 添加文字居中类
function setClass({ row, column, rowIndex, columnIndex }) {
  if (rowIndex === 0 && columnIndex === 4) {
    return 'textCenter'
  }
}
</script>

<style scoped lang="scss" name="ResourceApprove">
.resourceApprove {
  .search {
    @apply pb-30px;
  }
  .filename {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .dict-drop {
    display: inline-block;
    width: 7px;
    height: 7px;
    border-radius: 50%;
  }
  .pass {
    background-color: #67c23a;
  }
  .ing {
    background-color: #e6a23c;
  }
  :deep(.textCenter) {
    text-align: center !important;
  }
}
</style>
